package com.fanilycar51.mvp.mvpbase;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.fanilycar51.mvp.common.AppManager;
import com.fanilycar51.mvp.common.BusInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;

/**
 * 创建日期：2017/9/7  17:38
 * 描述:
 * 作者:张伟
 */

public abstract class BaseMvpActivity<V, P extends BasePresent> extends AppCompatActivity {
    //视图层持有的P层的对象d
    public P presenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getContentLayout());

        //视图绑定控件
        ButterKnife.bind(this);

        //初始化P层对象
        presenter = createPresenter();


        //设置6.0以后沉浸状体栏的问题
        setBar();

        //每次初始化的时候就将当前activity加入到全局的ActivityStack中
        AppManager.getInstance().add(this);

        //注册EventBus
        EventBus.getDefault().register(this);

    }


    /**
     * 获取布局的方法
     *
     * @return
     */
    protected abstract int getContentLayout();

    /**
     * 实例化P层对象
     */
    public abstract P createPresenter();


    protected abstract void initData();

    /**
     * EventBus的接受事件的方法
     *
     * @param busInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void busEvent(BusInfo busInfo) {

    }

    /**
     * 在onResume()方法中将视图层和P层进行绑定
     */
    @Override
    protected void onResume() {
        super.onResume();
        //讲P层和视图层绑定
        presenter.attach((V) this);

        //初始化数据
        initData();
    }


    /**
     * 设置沉浸状态栏的方法,需要在setContentView()之后调用
     */
    private void setBar() {
        //兼容5.0+，状态栏设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else
            //为了沉浸式状态栏 4.4以上才有
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
    }

    /**
     * 在OnDestroy()方法中解绑P层
     */
    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        presenter.detachView();
        super.onDestroy();
    }
}
